﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ActionSystem.Core.Utils;

namespace ActionSystem.Input
{
    [PoolInit(typeof(GeneticPool<InputBuffer>),20)]
    public class InputBuffer : IPoolItem
    {
        private ButtonType type = ButtonType.Unkonw;
        private int depth = 1;
        public int BuffDepth => depth;
        private Queue<InputButton> cache = new Queue<InputButton>();
        public Queue<InputButton> Cache => cache;
        public ButtonType Type { set { type = value; } get => type; }
        public void SetDepth(int depth)
        {
            foreach (var btn in cache)
            {
                if (btn != null)
                {
                    btn.PoolItemDelete();
                }
            }
            cache.Clear();
            this.depth = depth;
        }
        bool _isDown = false;
        public bool IsDown => _isDown;
        Vector2 _stickValue;
        public Vector2 StickValue => _stickValue;
        public void SetDown(bool down)
        {
            InputButton btn = null;
            if (_isDown != down)
            {
                btn = InputButton.Create();
                btn.Index = 0;
                if (down)
                {
                    btn.State = ButtonState.Down;
                }
                else
                {
                    btn.State = ButtonState.Up;
                }
            }
            _isDown = down;
            Cache.Enqueue(btn);
        }
        public void Clamp()
        {
            while (Cache.Count > depth)
            {
                Cache.Dequeue();
            }
        }
        public void SetStick(Vector2 value)
        {
            InputButton btn = InputButton.Create();
            btn.Index = 0;
            _stickValue = value;
            btn.Stick = _stickValue;
            Cache.Enqueue(btn);
        }        
        public bool IsDeleted { get; set; }

        public static InputBuffer Create()
        {
            return GeneticPool<InputBuffer>.Create();
        }

        public void PoolItemDelete()
        {
            foreach (var btn in cache)
            {
                if (btn != null)
                {
                    btn.PoolItemDelete();
                }
            }
            GeneticPool<InputBuffer>.Delete(this);
        }

        public void PoolItemReset()
        {
            depth = 1;
            type = ButtonType.Unkonw;            
            cache.Clear();
        }
    }
}

